jQuery(function($) {
	// Asynchronously Load the map API
	var script = document.createElement('script');
	script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
	document.body.appendChild(script);
});

function initialize() {
	$.mobile.loading('show');
	$.getJSON("data/markers.json", function(data) {
	}).success(function(data){
		var markers = new Array();
		for (var i = 0; i < data.markers.length; i++) {
			markers[i] = data.markers[i];
		}
				
		var map;
		var bounds = new google.maps.LatLngBounds();
		var mapOptions = {
			mapTypeId : 'roadmap'
		};

		// Display a map on the page
		map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
		map.setTilt(45);
		
		// Display multiple markers on a map
		var infoWindow = new google.maps.InfoWindow(), marker, i;

		// Loop through our array of markers & place each one on the map
		for (i = 0; i < markers.length; i++) {
			var position = new google.maps.LatLng(markers[i].lat, markers[i].lng);
			bounds.extend(position);
			marker = new google.maps.Marker({
				position : position,
				map : map,
				title : markers[i].title
			});

			// Allow each marker to have an info window
			google.maps.event.addListener(marker, 'click', (function(marker, i) {
				return function() {
					infoWindow.setContent('<div style="min-width: 200px;"><h3>' + markers[i].title + '</h3><p>' + markers[i].desc + '</p>');
					infoWindow.open(map, marker);
				}
			})(marker, i));

			// Automatically center the map fitting all markers on the screen
			map.fitBounds(bounds);
		}

		// Override our map zoom level once our fitBounds function runs (Make sure
		// it only runs once)
		var boundsListener = google.maps.event.addListener((map), 'bounds_changed',
				function(event) {
					this.setZoom(10);
					google.maps.event.removeListener(boundsListener);
				});
		});
	$.mobile.loading('hide');
}